home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / pydoc.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  88.5 KB  |  2,548 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Generate Python documentation in HTML or text for interactive use.
  5.  
  6. In the Python interpreter, do "from pydoc import help" to provide online
  7. help.  Calling help(thing) on a Python object documents the object.
  8.  
  9. Or, at the shell command line outside of Python:
  10.  
  11. Run "pydoc <name>" to show documentation on something.  <name> may be
  12. the name of a function, module, package, or a dotted reference to a
  13. class or function within a module or module in a package.  If the
  14. argument contains a path segment delimiter (e.g. slash on Unix,
  15. backslash on Windows) it is treated as the path to a Python source file.
  16.  
  17. Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
  18. of all available modules.
  19.  
  20. Run "pydoc -p <port>" to start an HTTP server on a given port on the
  21. local machine to generate documentation web pages.
  22.  
  23. For platforms without a command line, "pydoc -g" starts the HTTP server
  24. and also pops up a little window for controlling it.
  25.  
  26. Run "pydoc -w <name>" to write out the HTML documentation for a module
  27. to a file named "<name>.html".
  28.  
  29. Module docs for core modules are assumed to be in
  30.  
  31.     /usr/share/doc/pythonX.Y/html/library
  32.  
  33. if the pythonX.Y-doc package is installed or in
  34.  
  35.     http://docs.python.org/library/
  36.  
  37. This can be overridden by setting the PYTHONDOCS environment variable
  38. to a different URL or to a local directory containing the Library
  39. Reference Manual pages.
  40. '''
  41. __author__ = 'Ka-Ping Yee <ping@lfw.org>'
  42. __date__ = '26 February 2001'
  43. __version__ = '$Revision: 71447 $'
  44. __credits__ = 'Guido van Rossum, for an excellent programming language.\nTommy Burnette, the original creator of manpy.\nPaul Prescod, for all his work on onlinehelp.\nRichard Chamberlain, for the first implementation of textdoc.\n'
  45. import sys
  46. import imp
  47. import os
  48. import re
  49. import types
  50. import inspect
  51. import __builtin__
  52. import pkgutil
  53. from repr import Repr
  54. from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
  55.  
  56. try:
  57.     from collections import deque
  58. except ImportError:
  59.     
  60.     class deque(list):
  61.         
  62.         def popleft(self):
  63.             return self.pop(0)
  64.  
  65.  
  66.  
  67.  
  68. def pathdirs():
  69.     '''Convert sys.path into a list of absolute, existing, unique paths.'''
  70.     dirs = []
  71.     normdirs = []
  72.     for dir in sys.path:
  73.         if not dir:
  74.             pass
  75.         dir = os.path.abspath('.')
  76.         normdir = os.path.normcase(dir)
  77.         if normdir not in normdirs and os.path.isdir(dir):
  78.             dirs.append(dir)
  79.             normdirs.append(normdir)
  80.             continue
  81.     
  82.     return dirs
  83.  
  84.  
  85. def getdoc(object):
  86.     '''Get the doc string or comments for an object.'''
  87.     if not inspect.getdoc(object):
  88.         pass
  89.     result = inspect.getcomments(object)
  90.     if not result or re.sub('^ *\n', '', rstrip(result)):
  91.         pass
  92.     return ''
  93.  
  94.  
  95. def splitdoc(doc):
  96.     '''Split a doc string into a synopsis line (if any) and the rest.'''
  97.     lines = split(strip(doc), '\n')
  98.     if len(lines) == 1:
  99.         return (lines[0], '')
  100.     if len(lines) >= 2 and not rstrip(lines[1]):
  101.         return (lines[0], join(lines[2:], '\n'))
  102.     return ('', join(lines, '\n'))
  103.  
  104.  
  105. def classname(object, modname):
  106.     '''Get a class name and qualify it with a module name if necessary.'''
  107.     name = object.__name__
  108.     if object.__module__ != modname:
  109.         name = object.__module__ + '.' + name
  110.     
  111.     return name
  112.  
  113.  
  114. def isdata(object):
  115.     """Check if an object is of a type that probably means it's data."""
  116.     if not inspect.ismodule(object) and inspect.isclass(object) and inspect.isroutine(object) and inspect.isframe(object) and inspect.istraceback(object):
  117.         pass
  118.     return not inspect.iscode(object)
  119.  
  120.  
  121. def replace(text, *pairs):
  122.     '''Do a series of global replacements on a string.'''
  123.     while pairs:
  124.         text = join(split(text, pairs[0]), pairs[1])
  125.         pairs = pairs[2:]
  126.     return text
  127.  
  128.  
  129. def cram(text, maxlen):
  130.     '''Omit part of a string if needed to make it fit in a maximum length.'''
  131.     if len(text) > maxlen:
  132.         pre = max(0, (maxlen - 3) // 2)
  133.         post = max(0, maxlen - 3 - pre)
  134.         return text[:pre] + '...' + text[len(text) - post:]
  135.     return text
  136.  
  137. _re_stripid = re.compile(' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)
  138.  
  139. def stripid(text):
  140.     '''Remove the hexadecimal id from a Python object representation.'''
  141.     if _re_stripid.search(repr(Exception)):
  142.         return _re_stripid.sub('\\1', text)
  143.     return text
  144.  
  145.  
  146. def _is_some_method(obj):
  147.     if not inspect.ismethod(obj):
  148.         pass
  149.     return inspect.ismethoddescriptor(obj)
  150.  
  151.  
  152. def allmethods(cl):
  153.     methods = { }
  154.     for key, value in inspect.getmembers(cl, _is_some_method):
  155.         methods[key] = 1
  156.     
  157.     for base in cl.__bases__:
  158.         methods.update(allmethods(base))
  159.     
  160.     for key in methods.keys():
  161.         methods[key] = getattr(cl, key)
  162.     
  163.     return methods
  164.  
  165.  
  166. def _split_list(s, predicate):
  167.     '''Split sequence s via predicate, and return pair ([true], [false]).
  168.  
  169.     The return value is a 2-tuple of lists,
  170.         ([x for x in s if predicate(x)],
  171.          [x for x in s if not predicate(x)])
  172.     '''
  173.     yes = []
  174.     no = []
  175.     for x in s:
  176.         if predicate(x):
  177.             yes.append(x)
  178.             continue
  179.         no.append(x)
  180.     
  181.     return (yes, no)
  182.  
  183.  
  184. def visiblename(name, all = None):
  185.     '''Decide whether to show documentation on a variable.'''
  186.     _hidden_names = ('__builtins__', '__doc__', '__file__', '__path__', '__module__', '__name__', '__slots__', '__package__')
  187.     if name in _hidden_names:
  188.         return 0
  189.     if name.startswith('__') and name.endswith('__'):
  190.         return 1
  191.     if all is not None:
  192.         return name in all
  193.     return not name.startswith('_')
  194.  
  195.  
  196. def classify_class_attrs(object):
  197.     '''Wrap inspect.classify_class_attrs, with fixup for data descriptors.'''
  198.     
  199.     def fixup(data):
  200.         (name, kind, cls, value) = data
  201.         if inspect.isdatadescriptor(value):
  202.             kind = 'data descriptor'
  203.         
  204.         return (name, kind, cls, value)
  205.  
  206.     return map(fixup, inspect.classify_class_attrs(object))
  207.  
  208.  
  209. def ispackage(path):
  210.     '''Guess whether a path refers to a package directory.'''
  211.     if os.path.isdir(path):
  212.         for ext in ('.py', '.pyc', '.pyo'):
  213.             if os.path.isfile(os.path.join(path, '__init__' + ext)):
  214.                 return True
  215.         
  216.     
  217.     return False
  218.  
  219.  
  220. def source_synopsis(file):
  221.     line = file.readline()
  222.     while line[:1] == '#' or not strip(line):
  223.         line = file.readline()
  224.         if not line:
  225.             break
  226.             continue
  227.     line = strip(line)
  228.     if line[:4] == 'r"""':
  229.         line = line[1:]
  230.     
  231.     if line[:3] == '"""':
  232.         line = line[3:]
  233.         if line[-1:] == '\\':
  234.             line = line[:-1]
  235.         
  236.         while not strip(line):
  237.             line = file.readline()
  238.             if not line:
  239.                 break
  240.                 continue
  241.         result = strip(split(line, '"""')[0])
  242.     else:
  243.         result = None
  244.     return result
  245.  
  246.  
  247. def synopsis(filename, cache = { }):
  248.     '''Get the one-line summary out of a module file.'''
  249.     mtime = os.stat(filename).st_mtime
  250.     (lastupdate, result) = cache.get(filename, (0, None))
  251.     if lastupdate < mtime:
  252.         info = inspect.getmoduleinfo(filename)
  253.         
  254.         try:
  255.             file = open(filename)
  256.         except IOError:
  257.             return None
  258.  
  259.         if info and 'b' in info[2]:
  260.             
  261.             try:
  262.                 module = imp.load_module('__temp__', file, filename, info[1:])
  263.             except:
  264.                 return None
  265.  
  266.             if not module.__doc__:
  267.                 pass
  268.             result = ''.splitlines()[0]
  269.             del sys.modules['__temp__']
  270.         else:
  271.             result = source_synopsis(file)
  272.             file.close()
  273.         cache[filename] = (mtime, result)
  274.     
  275.     return result
  276.  
  277.  
  278. class ErrorDuringImport(Exception):
  279.     '''Errors that occurred while trying to import something to document it.'''
  280.     
  281.     def __init__(self, filename, exc_info):
  282.         (exc, value, tb) = exc_info
  283.         self.filename = filename
  284.         self.exc = exc
  285.         self.value = value
  286.         self.tb = tb
  287.  
  288.     
  289.     def __str__(self):
  290.         exc = self.exc
  291.         if type(exc) is types.ClassType:
  292.             exc = exc.__name__
  293.         
  294.         return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
  295.  
  296.  
  297.  
  298. def importfile(path):
  299.     '''Import a Python source file or compiled file given its path.'''
  300.     magic = imp.get_magic()
  301.     file = open(path, 'r')
  302.     if file.read(len(magic)) == magic:
  303.         kind = imp.PY_COMPILED
  304.     else:
  305.         kind = imp.PY_SOURCE
  306.     file.close()
  307.     filename = os.path.basename(path)
  308.     (name, ext) = os.path.splitext(filename)
  309.     file = open(path, 'r')
  310.     
  311.     try:
  312.         module = imp.load_module(name, file, path, (ext, 'r', kind))
  313.     except:
  314.         raise ErrorDuringImport(path, sys.exc_info())
  315.  
  316.     file.close()
  317.     return module
  318.  
  319.  
  320. def safeimport(path, forceload = 0, cache = { }):
  321.     """Import a module; handle errors; return None if the module isn't found.
  322.  
  323.     If the module *is* found but an exception occurs, it's wrapped in an
  324.     ErrorDuringImport exception and reraised.  Unlike __import__, if a
  325.     package path is specified, the module at the end of the path is returned,
  326.     not the package at the beginning.  If the optional 'forceload' argument
  327.     is 1, we reload the module from disk (unless it's a dynamic extension)."""
  328.     
  329.     try:
  330.         if forceload and path in sys.modules:
  331.             if path not in sys.builtin_module_names:
  332.                 subs = _[1]
  333.                 for key in [
  334.                     path] + subs:
  335.                     cache[key] = sys.modules[key]
  336.                     del sys.modules[key]
  337.                 
  338.             
  339.         
  340.         module = __import__(path)
  341.     except:
  342.         (exc, value, tb) = info = sys.exc_info()
  343.         if path in sys.modules:
  344.             raise ErrorDuringImport(sys.modules[path].__file__, info)
  345.         path in sys.modules
  346.         if exc is SyntaxError:
  347.             raise ErrorDuringImport(value.filename, info)
  348.         exc is SyntaxError
  349.         if exc is ImportError and split(lower(str(value)))[:2] == [
  350.             'no',
  351.             'module']:
  352.             return None
  353.         raise ErrorDuringImport(path, sys.exc_info())
  354.  
  355.     for part in split(path, '.')[1:]:
  356.         
  357.         try:
  358.             module = getattr(module, part)
  359.         continue
  360.         except AttributeError:
  361.             split(lower(str(value)))[:2] == [
  362.                 'no',
  363.                 'module']
  364.             split(lower(str(value)))[:2] == [
  365.                 'no',
  366.                 'module']
  367.             return None
  368.         
  369.  
  370.     
  371.     return module
  372.  
  373.  
  374. class Doc:
  375.     
  376.     def document(self, object, name = None, *args):
  377.         '''Generate documentation for an object.'''
  378.         args = (object, name) + args
  379.         if inspect.isgetsetdescriptor(object):
  380.             return self.docdata(*args)
  381.         if inspect.ismemberdescriptor(object):
  382.             return self.docdata(*args)
  383.         
  384.         try:
  385.             if inspect.ismodule(object):
  386.                 return self.docmodule(*args)
  387.             if inspect.isclass(object):
  388.                 return self.docclass(*args)
  389.             if inspect.isroutine(object):
  390.                 return self.docroutine(*args)
  391.         except AttributeError:
  392.             inspect.ismemberdescriptor(object)
  393.             inspect.ismemberdescriptor(object)
  394.             inspect.isgetsetdescriptor(object)
  395.         except:
  396.             inspect.ismemberdescriptor(object)
  397.  
  398.         if isinstance(object, property):
  399.             return self.docproperty(*args)
  400.         return self.docother(*args)
  401.  
  402.     
  403.     def fail(self, object, name = None, *args):
  404.         '''Raise an exception for unimplemented types.'''
  405.         if name:
  406.             pass
  407.         message = "don't know how to document object%s of type %s" % (' ' + repr(name), type(object).__name__)
  408.         raise TypeError, message
  409.  
  410.     docmodule = docclass = docroutine = docother = docproperty = docdata = fail
  411.     
  412.     def getdocloc(self, object):
  413.         '''Return the location of module docs or None'''
  414.         
  415.         try:
  416.             file = inspect.getabsfile(object)
  417.         except TypeError:
  418.             file = '(built-in)'
  419.  
  420.         docloc = os.environ.get('PYTHONDOCS', 'http://docs.python.org/library')
  421.         docdir = '/usr/share/doc/python%s/html/library' % sys.version[:3]
  422.         if not os.environ.has_key('PYTHONDOCS') and os.path.isdir(docdir):
  423.             docloc = docdir
  424.         
  425.         basedir = os.path.join(sys.exec_prefix, 'lib', 'python' + sys.version[0:3])
  426.         if isinstance(object, type(os)):
  427.             if (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', 'thread', 'zipimport') or file.startswith(basedir)) and not file.startswith(os.path.join(basedir, 'site-packages')):
  428.                 if docloc.startswith('http://'):
  429.                     docloc = '%s/%s' % (docloc.rstrip('/'), object.__name__)
  430.                 else:
  431.                     docloc = os.path.join(docloc, object.__name__ + '.html')
  432.             else:
  433.                 docloc = None
  434.         return docloc
  435.  
  436.  
  437.  
  438. class HTMLRepr(Repr):
  439.     '''Class for safely making an HTML representation of a Python object.'''
  440.     
  441.     def __init__(self):
  442.         Repr.__init__(self)
  443.         self.maxlist = self.maxtuple = 20
  444.         self.maxdict = 10
  445.         self.maxstring = self.maxother = 100
  446.  
  447.     
  448.     def escape(self, text):
  449.         return replace(text, '&', '&', '<', '<', '>', '>')
  450.  
  451.     
  452.     def repr(self, object):
  453.         return Repr.repr(self, object)
  454.  
  455.     
  456.     def repr1(self, x, level):
  457.         if hasattr(type(x), '__name__'):
  458.             methodname = 'repr_' + join(split(type(x).__name__), '_')
  459.             if hasattr(self, methodname):
  460.                 return getattr(self, methodname)(x, level)
  461.         
  462.         return self.escape(cram(stripid(repr(x)), self.maxother))
  463.  
  464.     
  465.     def repr_string(self, x, level):
  466.         test = cram(x, self.maxstring)
  467.         testrepr = repr(test)
  468.         if '\\' in test and '\\' not in replace(testrepr, '\\\\', ''):
  469.             return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
  470.         return re.sub('((\\\\[\\\\abfnrtv\\\'"]|\\\\[0-9]..|\\\\x..|\\\\u....)+)', '<font color="#c040c0">\\1</font>', self.escape(testrepr))
  471.  
  472.     repr_str = repr_string
  473.     
  474.     def repr_instance(self, x, level):
  475.         
  476.         try:
  477.             return self.escape(cram(stripid(repr(x)), self.maxstring))
  478.         except:
  479.             return self.escape('<%s instance>' % x.__class__.__name__)
  480.  
  481.  
  482.     repr_unicode = repr_string
  483.  
  484.  
  485. class HTMLDoc(Doc):
  486.     '''Formatter class for HTML documentation.'''
  487.     _repr_instance = HTMLRepr()
  488.     repr = _repr_instance.repr
  489.     escape = _repr_instance.escape
  490.     
  491.     def page(self, title, contents):
  492.         '''Format an HTML page.'''
  493.         return '\n<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\n<html><head><title>Python: %s</title>\n</head><body bgcolor="#f0f0f8">\n%s\n</body></html>' % (title, contents)
  494.  
  495.     
  496.     def heading(self, title, fgcol, bgcol, extras = ''):
  497.         '''Format a page heading.'''
  498.         if not extras:
  499.             pass
  500.         return '\n<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">\n<tr bgcolor="%s">\n<td valign=bottom> <br>\n<font color="%s" face="helvetica, arial"> <br>%s</font></td\n><td align=right valign=bottom\n><font color="%s" face="helvetica, arial">%s</font></td></tr></table>\n    ' % (bgcol, fgcol, title, fgcol, ' ')
  501.  
  502.     
  503.     def section(self, title, fgcol, bgcol, contents, width = 6, prelude = '', marginalia = None, gap = ' '):
  504.         '''Format a section with a heading.'''
  505.         if marginalia is None:
  506.             marginalia = '<tt>' + ' ' * width + '</tt>'
  507.         
  508.         result = '<p>\n<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">\n<tr bgcolor="%s">\n<td colspan=3 valign=bottom> <br>\n<font color="%s" face="helvetica, arial">%s</font></td></tr>\n    ' % (bgcol, fgcol, title)
  509.         if prelude:
  510.             result = result + '\n<tr bgcolor="%s"><td rowspan=2>%s</td>\n<td colspan=2>%s</td></tr>\n<tr><td>%s</td>' % (bgcol, marginalia, prelude, gap)
  511.         else:
  512.             result = result + '\n<tr><td bgcolor="%s">%s</td><td>%s</td>' % (bgcol, marginalia, gap)
  513.         return result + '\n<td width="100%%">%s</td></tr></table>' % contents
  514.  
  515.     
  516.     def bigsection(self, title, *args):
  517.         '''Format a section with a big heading.'''
  518.         title = '<big><strong>%s</strong></big>' % title
  519.         return self.section(title, *args)
  520.  
  521.     
  522.     def preformat(self, text):
  523.         '''Format literal preformatted text.'''
  524.         text = self.escape(expandtabs(text))
  525.         return replace(text, '\n\n', '\n \n', '\n\n', '\n \n', ' ', ' ', '\n', '<br>\n')
  526.  
  527.     
  528.     def multicolumn(self, list, format, cols = 4):
  529.         '''Format a list of items into a multi-column list.'''
  530.         result = ''
  531.         rows = (len(list) + cols - 1) / cols
  532.         for col in range(cols):
  533.             result = result + '<td width="%d%%" valign=top>' % 100 / cols
  534.             for i in range(rows * col, rows * col + rows):
  535.                 if i < len(list):
  536.                     result = result + format(list[i]) + '<br>\n'
  537.                     continue
  538.             
  539.             result = result + '</td>'
  540.         
  541.         return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
  542.  
  543.     
  544.     def grey(self, text):
  545.         return '<font color="#909090">%s</font>' % text
  546.  
  547.     
  548.     def namelink(self, name, *dicts):
  549.         '''Make a link for an identifier, given name-to-URL mappings.'''
  550.         for dict in dicts:
  551.             if name in dict:
  552.                 return '<a href="%s">%s</a>' % (dict[name], name)
  553.         
  554.         return name
  555.  
  556.     
  557.     def classlink(self, object, modname):
  558.         '''Make a link for a class.'''
  559.         name = object.__name__
  560.         module = sys.modules.get(object.__module__)
  561.         if hasattr(module, name) and getattr(module, name) is object:
  562.             return '<a href="%s.html#%s">%s</a>' % (module.__name__, name, classname(object, modname))
  563.         return classname(object, modname)
  564.  
  565.     
  566.     def modulelink(self, object):
  567.         '''Make a link for a module.'''
  568.         return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
  569.  
  570.     
  571.     def modpkglink(self, data):
  572.         '''Make a link for a module or package to display in an index.'''
  573.         (name, path, ispackage, shadowed) = data
  574.         if shadowed:
  575.             return self.grey(name)
  576.         if path:
  577.             url = '%s.%s.html' % (path, name)
  578.         else:
  579.             url = '%s.html' % name
  580.         if ispackage:
  581.             text = '<strong>%s</strong> (package)' % name
  582.         else:
  583.             text = name
  584.         return '<a href="%s">%s</a>' % (url, text)
  585.  
  586.     
  587.     def markup(self, text, escape = None, funcs = { }, classes = { }, methods = { }):
  588.         '''Mark up some plain text, given a context of symbols to look for.
  589.         Each context dictionary maps object names to anchor names.'''
  590.         if not escape:
  591.             pass
  592.         escape = self.escape
  593.         results = []
  594.         here = 0
  595.         pattern = re.compile('\\b((http|ftp)://\\S+[\\w/]|RFC[- ]?(\\d+)|PEP[- ]?(\\d+)|(self\\.)?(\\w+))')
  596.         while True:
  597.             match = pattern.search(text, here)
  598.             if not match:
  599.                 break
  600.             
  601.             (start, end) = match.span()
  602.             results.append(escape(text[here:start]))
  603.             (all, scheme, rfc, pep, selfdot, name) = match.groups()
  604.             if scheme:
  605.                 url = escape(all).replace('"', '"')
  606.                 results.append('<a href="%s">%s</a>' % (url, url))
  607.             elif rfc:
  608.                 url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
  609.                 results.append('<a href="%s">%s</a>' % (url, escape(all)))
  610.             elif pep:
  611.                 url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)
  612.                 results.append('<a href="%s">%s</a>' % (url, escape(all)))
  613.             elif text[end:end + 1] == '(':
  614.                 results.append(self.namelink(name, methods, funcs, classes))
  615.             elif selfdot:
  616.                 results.append('self.<strong>%s</strong>' % name)
  617.             else:
  618.                 results.append(self.namelink(name, classes))
  619.             here = end
  620.         results.append(escape(text[here:]))
  621.         return join(results, '')
  622.  
  623.     
  624.     def formattree(self, tree, modname, parent = None):
  625.         '''Produce HTML for a class tree as given by inspect.getclasstree().'''
  626.         result = ''
  627.         for entry in tree:
  628.             if type(entry) is type(()):
  629.                 (c, bases) = entry
  630.                 result = result + '<dt><font face="helvetica, arial">'
  631.                 result = result + self.classlink(c, modname)
  632.                 if bases and bases != (parent,):
  633.                     parents = []
  634.                     for base in bases:
  635.                         parents.append(self.classlink(base, modname))
  636.                     
  637.                     result = result + '(' + join(parents, ', ') + ')'
  638.                 
  639.                 result = result + '\n</font></dt>'
  640.                 continue
  641.             if type(entry) is type([]):
  642.                 result = result + '<dd>\n%s</dd>\n' % self.formattree(entry, modname, c)
  643.                 continue
  644.         
  645.         return '<dl>\n%s</dl>\n' % result
  646.  
  647.     
  648.     def docmodule(self, object, name = None, mod = None, *ignored):
  649.         '''Produce HTML documentation for a module object.'''
  650.         name = object.__name__
  651.         
  652.         try:
  653.             all = object.__all__
  654.         except AttributeError:
  655.             all = None
  656.  
  657.         parts = split(name, '.')
  658.         links = []
  659.         for i in range(len(parts) - 1):
  660.             links.append('<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i + 1], '.'), parts[i]))
  661.         
  662.         linkedname = join(links + parts[-1:], '.')
  663.         head = '<big><big><strong>%s</strong></big></big>' % linkedname
  664.         
  665.         try:
  666.             path = inspect.getabsfile(object)
  667.             url = path
  668.             if sys.platform == 'win32':
  669.                 import nturl2path
  670.                 url = nturl2path.pathname2url(path)
  671.             
  672.             filelink = '<a href="file:%s">%s</a>' % (url, path)
  673.         except TypeError:
  674.             filelink = '(built-in)'
  675.  
  676.         info = []
  677.         if hasattr(object, '__version__'):
  678.             version = str(object.__version__)
  679.             if version[:11] == '$Revision: ' and version[-1:] == '$':
  680.                 version = strip(version[11:-1])
  681.             
  682.             info.append('version %s' % self.escape(version))
  683.         
  684.         if hasattr(object, '__date__'):
  685.             info.append(self.escape(str(object.__date__)))
  686.         
  687.         if info:
  688.             head = head + ' (%s)' % join(info, ', ')
  689.         
  690.         docloc = self.getdocloc(object)
  691.         if docloc is not None:
  692.             docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals()
  693.         else:
  694.             docloc = ''
  695.         result = self.heading(head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink + docloc)
  696.         modules = inspect.getmembers(object, inspect.ismodule)
  697.         classes = []
  698.         cdict = { }
  699.         for key, value in inspect.getmembers(object, inspect.isclass):
  700.             if not all is not None:
  701.                 if not inspect.getmodule(value):
  702.                     pass
  703.                 if object is object:
  704.                     if visiblename(key, all):
  705.                         classes.append((key, value))
  706.                         cdict[key] = cdict[value] = '#' + key
  707.                     
  708.             visiblename(key, all)
  709.         
  710.         for key, value in classes:
  711.             for base in value.__bases__:
  712.                 key = base.__name__
  713.                 modname = base.__module__
  714.                 module = sys.modules.get(modname)
  715.                 if modname != name and module and hasattr(module, key):
  716.                     if getattr(module, key) is base:
  717.                         if key not in cdict:
  718.                             cdict[key] = cdict[base] = modname + '.html#' + key
  719.                         
  720.                     
  721.                 getattr(module, key) is base
  722.             
  723.         
  724.         funcs = []
  725.         fdict = { }
  726.         for key, value in inspect.getmembers(object, inspect.isroutine):
  727.             if all is not None and inspect.isbuiltin(value) or inspect.getmodule(value) is object:
  728.                 if visiblename(key, all):
  729.                     funcs.append((key, value))
  730.                     fdict[key] = '#-' + key
  731.                     if inspect.isfunction(value):
  732.                         fdict[value] = fdict[key]
  733.                     
  734.                 
  735.             visiblename(key, all)
  736.         
  737.         data = []
  738.         for key, value in inspect.getmembers(object, isdata):
  739.             if visiblename(key, all):
  740.                 data.append((key, value))
  741.                 continue
  742.         
  743.         doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
  744.         if doc:
  745.             pass
  746.         doc = '<tt>%s</tt>' % doc
  747.         result = result + '<p>%s</p>\n' % doc
  748.         if hasattr(object, '__path__'):
  749.             modpkgs = []
  750.             for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
  751.                 modpkgs.append((modname, name, ispkg, 0))
  752.             
  753.             modpkgs.sort()
  754.             contents = self.multicolumn(modpkgs, self.modpkglink)
  755.             result = result + self.bigsection('Package Contents', '#ffffff', '#aa55cc', contents)
  756.         elif modules:
  757.             contents = self.multicolumn(modules, (lambda key_value, s = self: s.modulelink(key_value[1])))
  758.             result = result + self.bigsection('Modules', '#ffffff', '#aa55cc', contents)
  759.         
  760.         if classes:
  761.             classlist = map((lambda key_value: key_value[1]), classes)
  762.             contents = [
  763.                 self.formattree(inspect.getclasstree(classlist, 1), name)]
  764.             for key, value in classes:
  765.                 contents.append(self.document(value, key, name, fdict, cdict))
  766.             
  767.             result = result + self.bigsection('Classes', '#ffffff', '#ee77aa', join(contents))
  768.         
  769.         if funcs:
  770.             contents = []
  771.             for key, value in funcs:
  772.                 contents.append(self.document(value, key, name, fdict, cdict))
  773.             
  774.             result = result + self.bigsection('Functions', '#ffffff', '#eeaa77', join(contents))
  775.         
  776.         if data:
  777.             contents = []
  778.             for key, value in data:
  779.                 contents.append(self.document(value, key))
  780.             
  781.             result = result + self.bigsection('Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
  782.         
  783.         if hasattr(object, '__author__'):
  784.             contents = self.markup(str(object.__author__), self.preformat)
  785.             result = result + self.bigsection('Author', '#ffffff', '#7799ee', contents)
  786.         
  787.         if hasattr(object, '__credits__'):
  788.             contents = self.markup(str(object.__credits__), self.preformat)
  789.             result = result + self.bigsection('Credits', '#ffffff', '#7799ee', contents)
  790.         
  791.         return result
  792.  
  793.     
  794.     def docclass(self, object, name = None, mod = None, funcs = { }, classes = { }, *ignored):
  795.         '''Produce HTML documentation for a class object.'''
  796.         realname = object.__name__
  797.         if not name:
  798.             pass
  799.         name = realname
  800.         bases = object.__bases__
  801.         contents = []
  802.         push = contents.append
  803.         
  804.         class HorizontalRule(()):
  805.             
  806.             def __init__(self):
  807.                 self.needone = 0
  808.  
  809.             
  810.             def maybe(self):
  811.                 if self.needone:
  812.                     push('<hr>\n')
  813.                 
  814.                 self.needone = 1
  815.  
  816.  
  817.         hr = HorizontalRule()
  818.         mro = deque(inspect.getmro(object))
  819.         if len(mro) > 2:
  820.             hr.maybe()
  821.             push('<dl><dt>Method resolution order:</dt>\n')
  822.             for base in mro:
  823.                 push('<dd>%s</dd>\n' % self.classlink(base, object.__module__))
  824.             
  825.             push('</dl>\n')
  826.         
  827.         
  828.         def spill(msg, attrs, predicate):
  829.             (ok, attrs) = _split_list(attrs, predicate)
  830.             if ok:
  831.                 hr.maybe()
  832.                 push(msg)
  833.                 for name, kind, homecls, value in ok:
  834.                     push(self.document(getattr(object, name), name, mod, funcs, classes, mdict, object))
  835.                     push('\n')
  836.                 
  837.             
  838.             return attrs
  839.  
  840.         
  841.         def spilldescriptors(msg, attrs, predicate):
  842.             (ok, attrs) = _split_list(attrs, predicate)
  843.             if ok:
  844.                 hr.maybe()
  845.                 push(msg)
  846.                 for name, kind, homecls, value in ok:
  847.                     push(self._docdescriptor(name, value, mod))
  848.                 
  849.             
  850.             return attrs
  851.  
  852.         
  853.         def spilldata(msg, attrs, predicate):
  854.             (ok, attrs) = _split_list(attrs, predicate)
  855.             if ok:
  856.                 hr.maybe()
  857.                 push(msg)
  858.                 for name, kind, homecls, value in ok:
  859.                     base = self.docother(getattr(object, name), name, mod)
  860.                     if hasattr(value, '__call__') or inspect.isdatadescriptor(value):
  861.                         doc = getattr(value, '__doc__', None)
  862.                     else:
  863.                         doc = None
  864.                     if doc is None:
  865.                         push('<dl><dt>%s</dl>\n' % base)
  866.                     else:
  867.                         doc = self.markup(getdoc(value), self.preformat, funcs, classes, mdict)
  868.                         doc = '<dd><tt>%s</tt>' % doc
  869.                         push('<dl><dt>%s%s</dl>\n' % (base, doc))
  870.                     push('\n')
  871.                 
  872.             
  873.             return attrs
  874.  
  875.         attrs = filter((lambda data: visiblename(data[0])), classify_class_attrs(object))
  876.         mdict = { }
  877.         for key, kind, homecls, value in attrs:
  878.             value = getattr(object, key)
  879.             
  880.             try:
  881.                 mdict[value] = anchor
  882.             continue
  883.             except TypeError:
  884.                 (None, None, None, None, None, None, None, (None, None, None, (None, None, None, None, None, None, None, None)))
  885.                 (None, None, None, None, None, None, None, (None, None, None, (None, None, None, None, None, None, None, None)))
  886.                 continue
  887.             
  888.  
  889.         
  890.         while attrs:
  891.             (attrs, inherited) = _split_list((attrs,), (lambda t: t[2] is thisclass))
  892.             if thisclass is __builtin__.object:
  893.                 attrs = inherited
  894.                 continue
  895.             elif thisclass is object:
  896.                 tag = 'defined here'
  897.             else:
  898.                 tag = 'inherited from %s' % self.classlink(thisclass, object.__module__)
  899.             tag += ':<br>\n'
  900.             
  901.             try:
  902.                 attrs.sort(key = (lambda t: t[0]))
  903.             except TypeError:
  904.                 attrs.sort((lambda t1, t2: cmp(t1[0], t2[0])))
  905.  
  906.             attrs = spill('Methods %s' % tag, attrs, (lambda t: t[1] == 'method'))
  907.             attrs = spill('Class methods %s' % tag, attrs, (lambda t: t[1] == 'class method'))
  908.             attrs = spill('Static methods %s' % tag, attrs, (lambda t: t[1] == 'static method'))
  909.             attrs = spilldescriptors('Data descriptors %s' % tag, attrs, (lambda t: t[1] == 'data descriptor'))
  910.             attrs = spilldata('Data and other attributes %s' % tag, attrs, (lambda t: t[1] == 'data'))
  911.             if not attrs == []:
  912.                 raise AssertionError
  913.             attrs = inherited
  914.             continue
  915.             attrs == []
  916.         contents = ''.join(contents)
  917.         if name == realname:
  918.             title = '<a name="%s">class <strong>%s</strong></a>' % (name, realname)
  919.         else:
  920.             title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (name, name, realname)
  921.         if bases:
  922.             parents = []
  923.             for base in bases:
  924.                 parents.append(self.classlink(base, object.__module__))
  925.             
  926.             title = title + '(%s)' % join(parents, ', ')
  927.         
  928.         doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)
  929.         if doc:
  930.             pass
  931.         doc = '<tt>%s<br> </tt>' % doc
  932.         return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)
  933.  
  934.     
  935.     def formatvalue(self, object):
  936.         '''Format an argument default value as text.'''
  937.         return self.grey('=' + self.repr(object))
  938.  
  939.     
  940.     def docroutine(self, object, name = None, mod = None, funcs = { }, classes = { }, methods = { }, cl = None):
  941.         '''Produce HTML documentation for a function or method object.'''
  942.         realname = object.__name__
  943.         if not name:
  944.             pass
  945.         name = realname
  946.         if not cl or cl.__name__:
  947.             pass
  948.         anchor = '' + '-' + name
  949.         note = ''
  950.         skipdocs = 0
  951.         if inspect.ismethod(object):
  952.             imclass = object.im_class
  953.             if cl:
  954.                 if imclass is not cl:
  955.                     note = ' from ' + self.classlink(imclass, mod)
  956.                 
  957.             elif object.im_self is not None:
  958.                 note = ' method of %s instance' % self.classlink(object.im_self.__class__, mod)
  959.             else:
  960.                 note = ' unbound %s method' % self.classlink(imclass, mod)
  961.             object = object.im_func
  962.         
  963.         if name == realname:
  964.             title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
  965.         elif cl and realname in cl.__dict__ and cl.__dict__[realname] is object:
  966.             reallink = '<a href="#%s">%s</a>' % (cl.__name__ + '-' + realname, realname)
  967.             skipdocs = 1
  968.         else:
  969.             reallink = realname
  970.         title = '<a name="%s"><strong>%s</strong></a> = %s' % (anchor, name, reallink)
  971.         if inspect.isfunction(object):
  972.             (args, varargs, varkw, defaults) = inspect.getargspec(object)
  973.             argspec = inspect.formatargspec(args, varargs, varkw, defaults, formatvalue = self.formatvalue)
  974.             if realname == '<lambda>':
  975.                 title = '<strong>%s</strong> <em>lambda</em> ' % name
  976.                 argspec = argspec[1:-1]
  977.             
  978.         else:
  979.             argspec = '(...)'
  980.         if note:
  981.             pass
  982.         decl = title + argspec + self.grey('<font face="helvetica, arial">%s</font>' % note)
  983.         if skipdocs:
  984.             return '<dl><dt>%s</dt></dl>\n' % decl
  985.         doc = self.markup(getdoc(object), self.preformat, funcs, classes, methods)
  986.         if doc:
  987.             pass
  988.         doc = '<dd><tt>%s</tt></dd>' % doc
  989.         return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
  990.  
  991.     
  992.     def _docdescriptor(self, name, value, mod):
  993.         results = []
  994.         push = results.append
  995.         if name:
  996.             push('<dl><dt><strong>%s</strong></dt>\n' % name)
  997.         
  998.         if value.__doc__ is not None:
  999.             doc = self.markup(getdoc(value), self.preformat)
  1000.             push('<dd><tt>%s</tt></dd>\n' % doc)
  1001.         
  1002.         push('</dl>\n')
  1003.         return ''.join(results)
  1004.  
  1005.     
  1006.     def docproperty(self, object, name = None, mod = None, cl = None):
  1007.         '''Produce html documentation for a property.'''
  1008.         return self._docdescriptor(name, object, mod)
  1009.  
  1010.     
  1011.     def docother(self, object, name = None, mod = None, *ignored):
  1012.         '''Produce HTML documentation for a data object.'''
  1013.         if not name or '<strong>%s</strong> = ' % name:
  1014.             pass
  1015.         lhs = ''
  1016.         return lhs + self.repr(object)
  1017.  
  1018.     
  1019.     def docdata(self, object, name = None, mod = None, cl = None):
  1020.         '''Produce html documentation for a data descriptor.'''
  1021.         return self._docdescriptor(name, object, mod)
  1022.  
  1023.     
  1024.     def index(self, dir, shadowed = None):
  1025.         '''Generate an HTML index for a directory of modules.'''
  1026.         modpkgs = []
  1027.         if shadowed is None:
  1028.             shadowed = { }
  1029.         
  1030.         for importer, name, ispkg in pkgutil.iter_modules([
  1031.             dir]):
  1032.             modpkgs.append((name, '', ispkg, name in shadowed))
  1033.             shadowed[name] = 1
  1034.         
  1035.         modpkgs.sort()
  1036.         contents = self.multicolumn(modpkgs, self.modpkglink)
  1037.         return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
  1038.  
  1039.  
  1040.  
  1041. class TextRepr(Repr):
  1042.     '''Class for safely making a text representation of a Python object.'''
  1043.     
  1044.     def __init__(self):
  1045.         Repr.__init__(self)
  1046.         self.maxlist = self.maxtuple = 20
  1047.         self.maxdict = 10
  1048.         self.maxstring = self.maxother = 100
  1049.  
  1050.     
  1051.     def repr1(self, x, level):
  1052.         if hasattr(type(x), '__name__'):
  1053.             methodname = 'repr_' + join(split(type(x).__name__), '_')
  1054.             if hasattr(self, methodname):
  1055.                 return getattr(self, methodname)(x, level)
  1056.         
  1057.         return cram(stripid(repr(x)), self.maxother)
  1058.  
  1059.     
  1060.     def repr_string(self, x, level):
  1061.         test = cram(x, self.maxstring)
  1062.         testrepr = repr(test)
  1063.         if '\\' in test and '\\' not in replace(testrepr, '\\\\', ''):
  1064.             return 'r' + testrepr[0] + test + testrepr[0]
  1065.         return testrepr
  1066.  
  1067.     repr_str = repr_string
  1068.     
  1069.     def repr_instance(self, x, level):
  1070.         
  1071.         try:
  1072.             return cram(stripid(repr(x)), self.maxstring)
  1073.         except:
  1074.             return '<%s instance>' % x.__class__.__name__
  1075.  
  1076.  
  1077.  
  1078.  
  1079. class TextDoc(Doc):
  1080.     '''Formatter class for text documentation.'''
  1081.     _repr_instance = TextRepr()
  1082.     repr = _repr_instance.repr
  1083.     
  1084.     def bold(self, text):
  1085.         '''Format a string in bold by overstriking.'''
  1086.         return join(map((lambda ch: ch + '\x08' + ch), text), '')
  1087.  
  1088.     
  1089.     def indent(self, text, prefix = '    '):
  1090.         '''Indent text by prepending a given prefix to each line.'''
  1091.         if not text:
  1092.             return ''
  1093.         lines = split(text, '\n')
  1094.         lines = map((lambda line, prefix = prefix: prefix + line), lines)
  1095.         if lines:
  1096.             lines[-1] = rstrip(lines[-1])
  1097.         
  1098.         return join(lines, '\n')
  1099.  
  1100.     
  1101.     def section(self, title, contents):
  1102.         '''Format a section with a given heading.'''
  1103.         return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
  1104.  
  1105.     
  1106.     def formattree(self, tree, modname, parent = None, prefix = ''):
  1107.         '''Render in text a class tree as returned by inspect.getclasstree().'''
  1108.         result = ''
  1109.         for entry in tree:
  1110.             if type(entry) is type(()):
  1111.                 (c, bases) = entry
  1112.                 result = result + prefix + classname(c, modname)
  1113.                 if bases and bases != (parent,):
  1114.                     parents = map((lambda c, m = modname: classname(c, m)), bases)
  1115.                     result = result + '(%s)' % join(parents, ', ')
  1116.                 
  1117.                 result = result + '\n'
  1118.                 continue
  1119.             if type(entry) is type([]):
  1120.                 result = result + self.formattree(entry, modname, c, prefix + '    ')
  1121.                 continue
  1122.         
  1123.         return result
  1124.  
  1125.     
  1126.     def docmodule(self, object, name = None, mod = None):
  1127.         '''Produce text documentation for a given module object.'''
  1128.         name = object.__name__
  1129.         (synop, desc) = splitdoc(getdoc(object))
  1130.         if synop:
  1131.             pass
  1132.         result = self.section('NAME', name + ' - ' + synop)
  1133.         
  1134.         try:
  1135.             all = object.__all__
  1136.         except AttributeError:
  1137.             all = None
  1138.  
  1139.         
  1140.         try:
  1141.             file = inspect.getabsfile(object)
  1142.         except TypeError:
  1143.             file = '(built-in)'
  1144.  
  1145.         result = result + self.section('FILE', file)
  1146.         docloc = self.getdocloc(object)
  1147.         if docloc is not None:
  1148.             result = result + self.section('MODULE DOCS', docloc)
  1149.         
  1150.         if desc:
  1151.             result = result + self.section('DESCRIPTION', desc)
  1152.         
  1153.         classes = []
  1154.         for key, value in inspect.getmembers(object, inspect.isclass):
  1155.             if not all is not None:
  1156.                 if not inspect.getmodule(value):
  1157.                     pass
  1158.                 if object is object:
  1159.                     if visiblename(key, all):
  1160.                         classes.append((key, value))
  1161.                     
  1162.             visiblename(key, all)
  1163.         
  1164.         funcs = []
  1165.         for key, value in inspect.getmembers(object, inspect.isroutine):
  1166.             if all is not None and inspect.isbuiltin(value) or inspect.getmodule(value) is object:
  1167.                 if visiblename(key, all):
  1168.                     funcs.append((key, value))
  1169.                 
  1170.             visiblename(key, all)
  1171.         
  1172.         data = []
  1173.         for key, value in inspect.getmembers(object, isdata):
  1174.             if visiblename(key, all):
  1175.                 data.append((key, value))
  1176.                 continue
  1177.         
  1178.         modpkgs = []
  1179.         modpkgs_names = set()
  1180.         if hasattr(object, '__path__'):
  1181.             for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
  1182.                 modpkgs_names.add(modname)
  1183.                 if ispkg:
  1184.                     modpkgs.append(modname + ' (package)')
  1185.                     continue
  1186.                 modpkgs.append(modname)
  1187.             
  1188.             modpkgs.sort()
  1189.             result = result + self.section('PACKAGE CONTENTS', join(modpkgs, '\n'))
  1190.         
  1191.         submodules = []
  1192.         for key, value in inspect.getmembers(object, inspect.ismodule):
  1193.             if value.__name__.startswith(name + '.') and key not in modpkgs_names:
  1194.                 submodules.append(key)
  1195.                 continue
  1196.         
  1197.         if submodules:
  1198.             submodules.sort()
  1199.             result = result + self.section('SUBMODULES', join(submodules, '\n'))
  1200.         
  1201.         if classes:
  1202.             classlist = map((lambda key_value: key_value[1]), classes)
  1203.             contents = [
  1204.                 self.formattree(inspect.getclasstree(classlist, 1), name)]
  1205.             for key, value in classes:
  1206.                 contents.append(self.document(value, key, name))
  1207.             
  1208.             result = result + self.section('CLASSES', join(contents, '\n'))
  1209.         
  1210.         if funcs:
  1211.             contents = []
  1212.             for key, value in funcs:
  1213.                 contents.append(self.document(value, key, name))
  1214.             
  1215.             result = result + self.section('FUNCTIONS', join(contents, '\n'))
  1216.         
  1217.         if data:
  1218.             contents = []
  1219.             for key, value in data:
  1220.                 contents.append(self.docother(value, key, name, maxlen = 70))
  1221.             
  1222.             result = result + self.section('DATA', join(contents, '\n'))
  1223.         
  1224.         if hasattr(object, '__version__'):
  1225.             version = str(object.__version__)
  1226.             if version[:11] == '$Revision: ' and version[-1:] == '$':
  1227.                 version = strip(version[11:-1])
  1228.             
  1229.             result = result + self.section('VERSION', version)
  1230.         
  1231.         if hasattr(object, '__date__'):
  1232.             result = result + self.section('DATE', str(object.__date__))
  1233.         
  1234.         if hasattr(object, '__author__'):
  1235.             result = result + self.section('AUTHOR', str(object.__author__))
  1236.         
  1237.         if hasattr(object, '__credits__'):
  1238.             result = result + self.section('CREDITS', str(object.__credits__))
  1239.         
  1240.         return result
  1241.  
  1242.     
  1243.     def docclass(self, object, name = None, mod = None):
  1244.         '''Produce text documentation for a given class object.'''
  1245.         realname = object.__name__
  1246.         if not name:
  1247.             pass
  1248.         name = realname
  1249.         bases = object.__bases__
  1250.         
  1251.         def makename(c, m = object.__module__):
  1252.             return classname(c, m)
  1253.  
  1254.         if name == realname:
  1255.             title = 'class ' + self.bold(realname)
  1256.         else:
  1257.             title = self.bold(name) + ' = class ' + realname
  1258.         if bases:
  1259.             parents = map(makename, bases)
  1260.             title = title + '(%s)' % join(parents, ', ')
  1261.         
  1262.         doc = getdoc(object)
  1263.         if not doc or [
  1264.             doc + '\n']:
  1265.             pass
  1266.         contents = []
  1267.         push = contents.append
  1268.         mro = deque(inspect.getmro(object))
  1269.         if len(mro) > 2:
  1270.             push('Method resolution order:')
  1271.             for base in mro:
  1272.                 push('    ' + makename(base))
  1273.             
  1274.             push('')
  1275.         
  1276.         
  1277.         class HorizontalRule(()):
  1278.             
  1279.             def __init__(self):
  1280.                 self.needone = 0
  1281.  
  1282.             
  1283.             def maybe(self):
  1284.                 if self.needone:
  1285.                     push('-' * 70)
  1286.                 
  1287.                 self.needone = 1
  1288.  
  1289.  
  1290.         hr = HorizontalRule()
  1291.         
  1292.         def spill(msg, attrs, predicate):
  1293.             (ok, attrs) = _split_list(attrs, predicate)
  1294.             if ok:
  1295.                 hr.maybe()
  1296.                 push(msg)
  1297.                 for name, kind, homecls, value in ok:
  1298.                     push(self.document(getattr(object, name), name, mod, object))
  1299.                 
  1300.             
  1301.             return attrs
  1302.  
  1303.         
  1304.         def spilldescriptors(msg, attrs, predicate):
  1305.             (ok, attrs) = _split_list(attrs, predicate)
  1306.             if ok:
  1307.                 hr.maybe()
  1308.                 push(msg)
  1309.                 for name, kind, homecls, value in ok:
  1310.                     push(self._docdescriptor(name, value, mod))
  1311.                 
  1312.             
  1313.             return attrs
  1314.  
  1315.         
  1316.         def spilldata(msg, attrs, predicate):
  1317.             (ok, attrs) = _split_list(attrs, predicate)
  1318.             if ok:
  1319.                 hr.maybe()
  1320.                 push(msg)
  1321.                 for name, kind, homecls, value in ok:
  1322.                     if hasattr(value, '__call__') or inspect.isdatadescriptor(value):
  1323.                         doc = getdoc(value)
  1324.                     else:
  1325.                         doc = None
  1326.                     push(self.docother(getattr(object, name), name, mod, maxlen = 70, doc = doc) + '\n')
  1327.                 
  1328.             
  1329.             return attrs
  1330.  
  1331.         attrs = filter((lambda data: visiblename(data[0])), classify_class_attrs(object))
  1332.         while attrs:
  1333.             if mro:
  1334.                 thisclass = mro.popleft()
  1335.             else:
  1336.                 thisclass = attrs[0][2]
  1337.             (attrs, inherited) = _split_list((attrs,), (lambda t: t[2] is thisclass))
  1338.             if thisclass is __builtin__.object:
  1339.                 attrs = inherited
  1340.                 continue
  1341.             elif thisclass is object:
  1342.                 tag = 'defined here'
  1343.             else:
  1344.                 tag = 'inherited from %s' % classname(thisclass, object.__module__)
  1345.             attrs.sort()
  1346.             attrs = spill('Methods %s:\n' % tag, attrs, (lambda t: t[1] == 'method'))
  1347.             attrs = spill('Class methods %s:\n' % tag, attrs, (lambda t: t[1] == 'class method'))
  1348.             attrs = spill('Static methods %s:\n' % tag, attrs, (lambda t: t[1] == 'static method'))
  1349.             attrs = spilldescriptors('Data descriptors %s:\n' % tag, attrs, (lambda t: t[1] == 'data descriptor'))
  1350.             attrs = spilldata('Data and other attributes %s:\n' % tag, attrs, (lambda t: t[1] == 'data'))
  1351.             if not attrs == []:
  1352.                 raise AssertionError
  1353.             attrs = inherited
  1354.             continue
  1355.             attrs == []
  1356.         contents = '\n'.join(contents)
  1357.         if not contents:
  1358.             return title + '\n'
  1359.         return title + '\n' + self.indent(rstrip(contents), ' |  ') + '\n'
  1360.  
  1361.     
  1362.     def formatvalue(self, object):
  1363.         '''Format an argument default value as text.'''
  1364.         return '=' + self.repr(object)
  1365.  
  1366.     
  1367.     def docroutine(self, object, name = None, mod = None, cl = None):
  1368.         '''Produce text documentation for a function or method object.'''
  1369.         realname = object.__name__
  1370.         if not name:
  1371.             pass
  1372.         name = realname
  1373.         note = ''
  1374.         skipdocs = 0
  1375.         if inspect.ismethod(object):
  1376.             imclass = object.im_class
  1377.             if cl:
  1378.                 if imclass is not cl:
  1379.                     note = ' from ' + classname(imclass, mod)
  1380.                 
  1381.             elif object.im_self is not None:
  1382.                 note = ' method of %s instance' % classname(object.im_self.__class__, mod)
  1383.             else:
  1384.                 note = ' unbound %s method' % classname(imclass, mod)
  1385.             object = object.im_func
  1386.         
  1387.         if name == realname:
  1388.             title = self.bold(realname)
  1389.         elif cl and realname in cl.__dict__ and cl.__dict__[realname] is object:
  1390.             skipdocs = 1
  1391.         
  1392.         title = self.bold(name) + ' = ' + realname
  1393.         if inspect.isfunction(object):
  1394.             (args, varargs, varkw, defaults) = inspect.getargspec(object)
  1395.             argspec = inspect.formatargspec(args, varargs, varkw, defaults, formatvalue = self.formatvalue)
  1396.             if realname == '<lambda>':
  1397.                 title = self.bold(name) + ' lambda '
  1398.                 argspec = argspec[1:-1]
  1399.             
  1400.         else:
  1401.             argspec = '(...)'
  1402.         decl = title + argspec + note
  1403.         if skipdocs:
  1404.             return decl + '\n'
  1405.         if not getdoc(object):
  1406.             pass
  1407.         doc = ''
  1408.         if doc:
  1409.             pass
  1410.         return decl + '\n' + rstrip(self.indent(doc)) + '\n'
  1411.  
  1412.     
  1413.     def _docdescriptor(self, name, value, mod):
  1414.         results = []
  1415.         push = results.append
  1416.         if name:
  1417.             push(self.bold(name))
  1418.             push('\n')
  1419.         
  1420.         if not getdoc(value):
  1421.             pass
  1422.         doc = ''
  1423.         if doc:
  1424.             push(self.indent(doc))
  1425.             push('\n')
  1426.         
  1427.         return ''.join(results)
  1428.  
  1429.     
  1430.     def docproperty(self, object, name = None, mod = None, cl = None):
  1431.         '''Produce text documentation for a property.'''
  1432.         return self._docdescriptor(name, object, mod)
  1433.  
  1434.     
  1435.     def docdata(self, object, name = None, mod = None, cl = None):
  1436.         '''Produce text documentation for a data descriptor.'''
  1437.         return self._docdescriptor(name, object, mod)
  1438.  
  1439.     
  1440.     def docother(self, object, name = None, mod = None, parent = None, maxlen = None, doc = None):
  1441.         '''Produce text documentation for a data object.'''
  1442.         repr = self.repr(object)
  1443.         if maxlen:
  1444.             if not name or name + ' = ':
  1445.                 pass
  1446.             line = '' + repr
  1447.             chop = maxlen - len(line)
  1448.             if chop < 0:
  1449.                 repr = repr[:chop] + '...'
  1450.             
  1451.         
  1452.         if not name or self.bold(name) + ' = ':
  1453.             pass
  1454.         line = '' + repr
  1455.         if doc is not None:
  1456.             line += '\n' + self.indent(str(doc))
  1457.         
  1458.         return line
  1459.  
  1460.  
  1461.  
  1462. def pager(text):
  1463.     '''The first time this is called, determine what kind of pager to use.'''
  1464.     global pager
  1465.     pager = getpager()
  1466.     pager(text)
  1467.  
  1468.  
  1469. def getpager():
  1470.     '''Decide what method to use for paging through text.'''
  1471.     if type(sys.stdout) is not types.FileType:
  1472.         return plainpager
  1473.     if not sys.stdin.isatty() or not sys.stdout.isatty():
  1474.         return plainpager
  1475.     if 'PAGER' in os.environ:
  1476.         if sys.platform == 'win32':
  1477.             return (lambda text: tempfilepager(plain(text), os.environ['PAGER']))
  1478.         if os.environ.get('TERM') in ('dumb', 'emacs'):
  1479.             return (lambda text: pipepager(plain(text), os.environ['PAGER']))
  1480.         return (lambda text: pipepager(text, os.environ['PAGER']))
  1481.     'PAGER' in os.environ
  1482.     if os.environ.get('TERM') in ('dumb', 'emacs'):
  1483.         return plainpager
  1484.     if sys.platform == 'win32' or sys.platform.startswith('os2'):
  1485.         return (lambda text: tempfilepager(plain(text), 'more <'))
  1486.     if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
  1487.         return (lambda text: pipepager(text, 'less'))
  1488.     import tempfile
  1489.     (fd, filename) = tempfile.mkstemp()
  1490.     os.close(fd)
  1491.     
  1492.     try:
  1493.         if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
  1494.             return (lambda text: pipepager(text, 'more'))
  1495.         return ttypager
  1496.     finally:
  1497.         os.unlink(filename)
  1498.  
  1499.  
  1500.  
  1501. def plain(text):
  1502.     '''Remove boldface formatting from text.'''
  1503.     return re.sub('.\x08', '', text)
  1504.  
  1505.  
  1506. def pipepager(text, cmd):
  1507.     '''Page through text by feeding it to another program.'''
  1508.     pipe = os.popen(cmd, 'w')
  1509.     
  1510.     try:
  1511.         pipe.write(text)
  1512.         pipe.close()
  1513.     except IOError:
  1514.         pass
  1515.  
  1516.  
  1517.  
  1518. def tempfilepager(text, cmd):
  1519.     '''Page through text by invoking a program on a temporary file.'''
  1520.     import tempfile
  1521.     filename = tempfile.mktemp()
  1522.     file = open(filename, 'w')
  1523.     file.write(text)
  1524.     file.close()
  1525.     
  1526.     try:
  1527.         os.system(cmd + ' "' + filename + '"')
  1528.     finally:
  1529.         os.unlink(filename)
  1530.  
  1531.  
  1532.  
  1533. def ttypager(text):
  1534.     '''Page through text on a text terminal.'''
  1535.     lines = split(plain(text), '\n')
  1536.     
  1537.     try:
  1538.         import tty
  1539.         fd = sys.stdin.fileno()
  1540.         old = tty.tcgetattr(fd)
  1541.         tty.setcbreak(fd)
  1542.         
  1543.         getchar = lambda : sys.stdin.read(1)
  1544.     except (ImportError, AttributeError):
  1545.         tty = None
  1546.         
  1547.         getchar = lambda : sys.stdin.readline()[:-1][:1]
  1548.  
  1549.     
  1550.     try:
  1551.         r = inc = os.environ.get('LINES', 25) - 1
  1552.         sys.stdout.write(join(lines[:inc], '\n') + '\n')
  1553.         while lines[r:]:
  1554.             sys.stdout.write('-- more --')
  1555.             sys.stdout.flush()
  1556.             c = getchar()
  1557.             if c in ('q', 'Q'):
  1558.                 sys.stdout.write('\r          \r')
  1559.                 break
  1560.             elif c in ('\r', '\n'):
  1561.                 sys.stdout.write('\r          \r' + lines[r] + '\n')
  1562.                 r = r + 1
  1563.                 continue
  1564.             
  1565.             if c in ('b', 'B', '\x1b'):
  1566.                 r = r - inc - inc
  1567.                 if r < 0:
  1568.                     r = 0
  1569.                 
  1570.             
  1571.             sys.stdout.write('\n' + join(lines[r:r + inc], '\n') + '\n')
  1572.             r = r + inc
  1573.     finally:
  1574.         if tty:
  1575.             tty.tcsetattr(fd, tty.TCSAFLUSH, old)
  1576.         
  1577.  
  1578.  
  1579.  
  1580. def plainpager(text):
  1581.     '''Simply print unformatted text.  This is the ultimate fallback.'''
  1582.     sys.stdout.write(plain(text))
  1583.  
  1584.  
  1585. def describe(thing):
  1586.     '''Produce a short description of the given thing.'''
  1587.     if inspect.ismodule(thing):
  1588.         if thing.__name__ in sys.builtin_module_names:
  1589.             return 'built-in module ' + thing.__name__
  1590.         if hasattr(thing, '__path__'):
  1591.             return 'package ' + thing.__name__
  1592.         return 'module ' + thing.__name__
  1593.     inspect.ismodule(thing)
  1594.     if inspect.isbuiltin(thing):
  1595.         return 'built-in function ' + thing.__name__
  1596.     if inspect.isgetsetdescriptor(thing):
  1597.         return 'getset descriptor %s.%s.%s' % (thing.__objclass__.__module__, thing.__objclass__.__name__, thing.__name__)
  1598.     if inspect.ismemberdescriptor(thing):
  1599.         return 'member descriptor %s.%s.%s' % (thing.__objclass__.__module__, thing.__objclass__.__name__, thing.__name__)
  1600.     if inspect.isclass(thing):
  1601.         return 'class ' + thing.__name__
  1602.     if inspect.isfunction(thing):
  1603.         return 'function ' + thing.__name__
  1604.     if inspect.ismethod(thing):
  1605.         return 'method ' + thing.__name__
  1606.     if type(thing) is types.InstanceType:
  1607.         return 'instance of ' + thing.__class__.__name__
  1608.     return type(thing).__name__
  1609.  
  1610.  
  1611. def locate(path, forceload = 0):
  1612.     '''Locate an object by name or dotted path, importing as necessary.'''
  1613.     parts = _[1]
  1614.     (module, n) = (None, 0)
  1615.     while n < len(parts):
  1616.         nextmodule = safeimport(join(parts[:n + 1], '.'), forceload)
  1617.         if nextmodule:
  1618.             module = nextmodule
  1619.             n = n + 1
  1620.             continue
  1621.         []
  1622.         break
  1623.         continue
  1624.         []
  1625.     if module:
  1626.         object = module
  1627.         for part in parts[n:]:
  1628.             
  1629.             try:
  1630.                 object = getattr(object, part)
  1631.             continue
  1632.             except AttributeError:
  1633.                 return None
  1634.             
  1635.  
  1636.         
  1637.         return object
  1638.     if hasattr(__builtin__, path):
  1639.         return getattr(__builtin__, path)
  1640.  
  1641. text = TextDoc()
  1642. html = HTMLDoc()
  1643.  
  1644. class _OldStyleClass:
  1645.     pass
  1646.  
  1647. _OLD_INSTANCE_TYPE = type(_OldStyleClass())
  1648.  
  1649. def resolve(thing, forceload = 0):
  1650.     '''Given an object or a path to an object, get the object and its name.'''
  1651.     if isinstance(thing, str):
  1652.         object = locate(thing, forceload)
  1653.         if not object:
  1654.             raise ImportError, 'no Python documentation found for %r' % thing
  1655.         object
  1656.         return (object, thing)
  1657.     return (thing, getattr(thing, '__name__', None))
  1658.  
  1659.  
  1660. def render_doc(thing, title = 'Python Library Documentation: %s', forceload = 0):
  1661.     '''Render text documentation, given an object or a path to an object.'''
  1662.     (object, name) = resolve(thing, forceload)
  1663.     desc = describe(object)
  1664.     module = inspect.getmodule(object)
  1665.     if name and '.' in name:
  1666.         desc += ' in ' + name[:name.rfind('.')]
  1667.     elif module and module is not object:
  1668.         desc += ' in module ' + module.__name__
  1669.     
  1670.     if type(object) is _OLD_INSTANCE_TYPE:
  1671.         object = object.__class__
  1672.     elif not inspect.ismodule(object) and inspect.isclass(object) and inspect.isroutine(object) and inspect.isgetsetdescriptor(object) and inspect.ismemberdescriptor(object) or isinstance(object, property):
  1673.         object = type(object)
  1674.         desc += ' object'
  1675.     
  1676.     return title % desc + '\n\n' + text.document(object, name)
  1677.  
  1678.  
  1679. def doc(thing, title = 'Python Library Documentation: %s', forceload = 0):
  1680.     '''Display text documentation, given an object or a path to an object.'''
  1681.     
  1682.     try:
  1683.         pager(render_doc(thing, title, forceload))
  1684.     except (ImportError, ErrorDuringImport):
  1685.         value = None
  1686.         print value
  1687.  
  1688.  
  1689.  
  1690. def writedoc(thing, forceload = 0):
  1691.     '''Write HTML documentation to a file in the current directory.'''
  1692.     
  1693.     try:
  1694.         (object, name) = resolve(thing, forceload)
  1695.         page = html.page(describe(object), html.document(object, name))
  1696.         file = open(name + '.html', 'w')
  1697.         file.write(page)
  1698.         file.close()
  1699.         print 'wrote', name + '.html'
  1700.     except (ImportError, ErrorDuringImport):
  1701.         value = None
  1702.         print value
  1703.  
  1704.  
  1705.  
  1706. def writedocs(dir, pkgpath = '', done = None):
  1707.     '''Write out HTML documentation for all modules in a directory tree.'''
  1708.     if done is None:
  1709.         done = { }
  1710.     
  1711.     for importer, modname, ispkg in pkgutil.walk_packages([
  1712.         dir], pkgpath):
  1713.         writedoc(modname)
  1714.     
  1715.  
  1716.  
  1717. class Helper:
  1718.     keywords = {
  1719.         'and': 'BOOLEAN',
  1720.         'as': 'with',
  1721.         'assert': ('assert', ''),
  1722.         'break': ('break', 'while for'),
  1723.         'class': ('class', 'CLASSES SPECIALMETHODS'),
  1724.         'continue': ('continue', 'while for'),
  1725.         'def': ('function', ''),
  1726.         'del': ('del', 'BASICMETHODS'),
  1727.         'elif': 'if',
  1728.         'else': ('else', 'while for'),
  1729.         'except': 'try',
  1730.         'exec': ('exec', ''),
  1731.         'finally': 'try',
  1732.         'for': ('for', 'break continue while'),
  1733.         'from': 'import',
  1734.         'global': ('global', 'NAMESPACES'),
  1735.         'if': ('if', 'TRUTHVALUE'),
  1736.         'import': ('import', 'MODULES'),
  1737.         'in': ('in', 'SEQUENCEMETHODS2'),
  1738.         'is': 'COMPARISON',
  1739.         'lambda': ('lambda', 'FUNCTIONS'),
  1740.         'not': 'BOOLEAN',
  1741.         'or': 'BOOLEAN',
  1742.         'pass': ('pass', ''),
  1743.         'print': ('print', ''),
  1744.         'raise': ('raise', 'EXCEPTIONS'),
  1745.         'return': ('return', 'FUNCTIONS'),
  1746.         'try': ('try', 'EXCEPTIONS'),
  1747.         'while': ('while', 'break continue if TRUTHVALUE'),
  1748.         'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
  1749.         'yield': ('yield', '') }
  1750.     _symbols_inverse = {
  1751.         'STRINGS': ("'", "'''", "r'", "u'", '"""', '"', 'r"', 'u"'),
  1752.         'OPERATORS': ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&', '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'),
  1753.         'COMPARISON': ('<', '>', '<=', '>=', '==', '!=', '<>'),
  1754.         'UNARY': ('-', '~'),
  1755.         'AUGMENTEDASSIGNMENT': ('+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '<<=', '>>=', '**=', '//='),
  1756.         'BITWISE': ('<<', '>>', '&', '|', '^', '~'),
  1757.         'COMPLEX': ('j', 'J') }
  1758.     symbols = {
  1759.         '%': 'OPERATORS FORMATTING',
  1760.         '**': 'POWER',
  1761.         ',': 'TUPLES LISTS FUNCTIONS',
  1762.         '.': 'ATTRIBUTES FLOAT MODULES OBJECTS',
  1763.         '...': 'ELLIPSIS',
  1764.         ':': 'SLICINGS DICTIONARYLITERALS',
  1765.         '@': 'def class',
  1766.         '\\': 'STRINGS',
  1767.         '_': 'PRIVATENAMES',
  1768.         '__': 'PRIVATENAMES SPECIALMETHODS',
  1769.         '`': 'BACKQUOTES',
  1770.         '(': 'TUPLES FUNCTIONS CALLS',
  1771.         ')': 'TUPLES FUNCTIONS CALLS',
  1772.         '[': 'LISTS SUBSCRIPTS SLICINGS',
  1773.         ']': 'LISTS SUBSCRIPTS SLICINGS' }
  1774.     for topic, symbols_ in _symbols_inverse.iteritems():
  1775.         for symbol in symbols_:
  1776.             topics = symbols.get(symbol, topic)
  1777.             if topic not in topics:
  1778.                 topics = topics + ' ' + topic
  1779.             
  1780.             symbols[symbol] = topics
  1781.         
  1782.     
  1783.     topics = {
  1784.         'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS FUNCTIONS CLASSES MODULES FILES inspect'),
  1785.         'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING TYPES'),
  1786.         'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'),
  1787.         'FORMATTING': ('formatstrings', 'OPERATORS'),
  1788.         'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS FORMATTING TYPES'),
  1789.         'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'),
  1790.         'INTEGER': ('integers', 'int range'),
  1791.         'FLOAT': ('floating', 'float math'),
  1792.         'COMPLEX': ('imaginary', 'complex cmath'),
  1793.         'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'),
  1794.         'MAPPINGS': 'DICTIONARIES',
  1795.         'FUNCTIONS': ('typesfunctions', 'def TYPES'),
  1796.         'METHODS': ('typesmethods', 'class def CLASSES TYPES'),
  1797.         'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'),
  1798.         'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'),
  1799.         'FRAMEOBJECTS': 'TYPES',
  1800.         'TRACEBACKS': 'TYPES',
  1801.         'NONE': ('bltin-null-object', ''),
  1802.         'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'),
  1803.         'FILES': ('bltin-file-objects', ''),
  1804.         'SPECIALATTRIBUTES': ('specialattrs', ''),
  1805.         'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'),
  1806.         'MODULES': ('typesmodules', 'import'),
  1807.         'PACKAGES': 'import',
  1808.         'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES LISTS DICTIONARIES BACKQUOTES'),
  1809.         'OPERATORS': 'EXPRESSIONS',
  1810.         'PRECEDENCE': 'EXPRESSIONS',
  1811.         'OBJECTS': ('objects', 'TYPES'),
  1812.         'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'),
  1813.         'BASICMETHODS': ('customization', 'cmp hash repr str SPECIALMETHODS'),
  1814.         'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
  1815.         'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'),
  1816.         'SEQUENCEMETHODS1': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS2 SPECIALMETHODS'),
  1817.         'SEQUENCEMETHODS2': ('sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 SPECIALMETHODS'),
  1818.         'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'),
  1819.         'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT SPECIALMETHODS'),
  1820.         'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
  1821.         'NAMESPACES': ('naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'),
  1822.         'DYNAMICFEATURES': ('dynamic-features', ''),
  1823.         'SCOPING': 'NAMESPACES',
  1824.         'FRAMES': 'NAMESPACES',
  1825.         'EXCEPTIONS': ('exceptions', 'try except finally raise'),
  1826.         'COERCIONS': ('coercion-rules', 'CONVERSIONS'),
  1827.         'CONVERSIONS': ('conversions', 'COERCIONS'),
  1828.         'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'),
  1829.         'SPECIALIDENTIFIERS': ('id-classes', ''),
  1830.         'PRIVATENAMES': ('atom-identifiers', ''),
  1831.         'LITERALS': ('atom-literals', 'STRINGS BACKQUOTES NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'),
  1832.         'TUPLES': 'SEQUENCES',
  1833.         'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'),
  1834.         'LISTS': ('typesseq-mutable', 'LISTLITERALS'),
  1835.         'LISTLITERALS': ('lists', 'LISTS LITERALS'),
  1836.         'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'),
  1837.         'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'),
  1838.         'BACKQUOTES': ('string-conversions', 'repr str STRINGS LITERALS'),
  1839.         'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'),
  1840.         'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS1'),
  1841.         'SLICINGS': ('slicings', 'SEQUENCEMETHODS2'),
  1842.         'CALLS': ('calls', 'EXPRESSIONS'),
  1843.         'POWER': ('power', 'EXPRESSIONS'),
  1844.         'UNARY': ('unary', 'EXPRESSIONS'),
  1845.         'BINARY': ('binary', 'EXPRESSIONS'),
  1846.         'SHIFTING': ('shifting', 'EXPRESSIONS'),
  1847.         'BITWISE': ('bitwise', 'EXPRESSIONS'),
  1848.         'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'),
  1849.         'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'),
  1850.         'ASSERTION': 'assert',
  1851.         'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'),
  1852.         'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'),
  1853.         'DELETION': 'del',
  1854.         'PRINTING': 'print',
  1855.         'RETURNING': 'return',
  1856.         'IMPORTING': 'import',
  1857.         'CONDITIONAL': 'if',
  1858.         'LOOPING': ('compound', 'for while break continue'),
  1859.         'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'),
  1860.         'DEBUGGING': ('debugger', 'pdb'),
  1861.         'CONTEXTMANAGERS': ('context-managers', 'with') }
  1862.     
  1863.     def __init__(self, input, output):
  1864.         self.input = input
  1865.         self.output = output
  1866.  
  1867.     
  1868.     def __repr__(self):
  1869.         if inspect.stack()[1][3] == '?':
  1870.             self()
  1871.             return ''
  1872.         return '<pydoc.Helper instance>'
  1873.  
  1874.     
  1875.     def __call__(self, request = None):
  1876.         if request is not None:
  1877.             self.help(request)
  1878.         else:
  1879.             self.intro()
  1880.             self.interact()
  1881.             self.output.write('\nYou are now leaving help and returning to the Python interpreter.\nIf you want to ask for help on a particular object directly from the\ninterpreter, you can type "help(object)".  Executing "help(\'string\')"\nhas the same effect as typing a particular string at the help> prompt.\n')
  1882.  
  1883.     
  1884.     def interact(self):
  1885.         self.output.write('\n')
  1886.         while True:
  1887.             
  1888.             try:
  1889.                 request = self.getline('help> ')
  1890.                 if not request:
  1891.                     break
  1892.             except (KeyboardInterrupt, EOFError):
  1893.                 break
  1894.  
  1895.             request = strip(replace(request, '"', '', "'", ''))
  1896.             if lower(request) in ('q', 'quit'):
  1897.                 break
  1898.             
  1899.             self.help(request)
  1900.  
  1901.     
  1902.     def getline(self, prompt):
  1903.         '''Read one line, using raw_input when available.'''
  1904.         if self.input is sys.stdin:
  1905.             return raw_input(prompt)
  1906.         self.output.write(prompt)
  1907.         self.output.flush()
  1908.         return self.input.readline()
  1909.  
  1910.     
  1911.     def help(self, request):
  1912.         if type(request) is type(''):
  1913.             if request == 'help':
  1914.                 self.intro()
  1915.             elif request == 'keywords':
  1916.                 self.listkeywords()
  1917.             elif request == 'symbols':
  1918.                 self.listsymbols()
  1919.             elif request == 'topics':
  1920.                 self.listtopics()
  1921.             elif request == 'modules':
  1922.                 self.listmodules()
  1923.             elif request[:8] == 'modules ':
  1924.                 self.listmodules(split(request)[1])
  1925.             elif request in self.symbols:
  1926.                 self.showsymbol(request)
  1927.             elif request in self.keywords:
  1928.                 self.showtopic(request)
  1929.             elif request in self.topics:
  1930.                 self.showtopic(request)
  1931.             elif request:
  1932.                 doc(request, 'Help on %s:')
  1933.             
  1934.         elif isinstance(request, Helper):
  1935.             self()
  1936.         else:
  1937.             doc(request, 'Help on %s:')
  1938.         self.output.write('\n')
  1939.  
  1940.     
  1941.     def intro(self):
  1942.         self.output.write('\nWelcome to Python %s!  This is the online help utility.\n\nIf this is your first time using Python, you should definitely check out\nthe tutorial on the Internet at http://docs.python.org/tutorial/.\n\nEnter the name of any module, keyword, or topic to get help on writing\nPython programs and using Python modules.  To quit this help utility and\nreturn to the interpreter, just type "quit".\n\nTo get a list of available modules, keywords, or topics, type "modules",\n"keywords", or "topics".  Each module also comes with a one-line summary\nof what it does; to list the modules whose summaries contain a given word\nsuch as "spam", type "modules spam".\n' % sys.version[:3])
  1943.  
  1944.     
  1945.     def list(self, items, columns = 4, width = 80):
  1946.         items = items[:]
  1947.         items.sort()
  1948.         colw = width / columns
  1949.         rows = (len(items) + columns - 1) / columns
  1950.         for row in range(rows):
  1951.             for col in range(columns):
  1952.                 i = col * rows + row
  1953.                 if i < len(items):
  1954.                     self.output.write(items[i])
  1955.                     if col < columns - 1:
  1956.                         self.output.write(' ' + ' ' * (colw - 1 - len(items[i])))
  1957.                     
  1958.                 col < columns - 1
  1959.             
  1960.             self.output.write('\n')
  1961.         
  1962.  
  1963.     
  1964.     def listkeywords(self):
  1965.         self.output.write('\nHere is a list of the Python keywords.  Enter any keyword to get more help.\n\n')
  1966.         self.list(self.keywords.keys())
  1967.  
  1968.     
  1969.     def listsymbols(self):
  1970.         self.output.write('\nHere is a list of the punctuation symbols which Python assigns special meaning\nto. Enter any symbol to get more help.\n\n')
  1971.         self.list(self.symbols.keys())
  1972.  
  1973.     
  1974.     def listtopics(self):
  1975.         self.output.write('\nHere is a list of available topics.  Enter any topic name to get more help.\n\n')
  1976.         self.list(self.topics.keys())
  1977.  
  1978.     
  1979.     def showtopic(self, topic, more_xrefs = ''):
  1980.         
  1981.         try:
  1982.             import pydoc_topics
  1983.         except ImportError:
  1984.             self.output.write('\nSorry, topic and keyword documentation is not available because the\nmodule "pydoc_topics" could not be found.\n')
  1985.             return None
  1986.  
  1987.         target = self.topics.get(topic, self.keywords.get(topic))
  1988.         if not target:
  1989.             self.output.write('no documentation found for %s\n' % repr(topic))
  1990.             return None
  1991.         if type(target) is type(''):
  1992.             return self.showtopic(target, more_xrefs)
  1993.         (label, xrefs) = target
  1994.         
  1995.         try:
  1996.             doc = pydoc_topics.topics[label]
  1997.         except KeyError:
  1998.             type(target) is type('')
  1999.             type(target) is type('')
  2000.             target
  2001.             self.output.write('no documentation found for %s\n' % repr(topic))
  2002.             return None
  2003.  
  2004.         pager(strip(doc) + '\n')
  2005.         if xrefs:
  2006.             import StringIO
  2007.             import formatter
  2008.             buffer = StringIO.StringIO()
  2009.             formatter.DumbWriter(buffer).send_flowing_data('Related help topics: ' + join(split(xrefs), ', ') + '\n')
  2010.             self.output.write('\n%s\n' % buffer.getvalue())
  2011.         
  2012.  
  2013.     
  2014.     def showsymbol(self, symbol):
  2015.         target = self.symbols[symbol]
  2016.         (topic, _, xrefs) = target.partition(' ')
  2017.         self.showtopic(topic, xrefs)
  2018.  
  2019.     
  2020.     def listmodules(self, key = ''):
  2021.         pass
  2022.  
  2023.  
  2024. help = Helper(sys.stdin, sys.stdout)
  2025.  
  2026. class Scanner:
  2027.     '''A generic tree iterator.'''
  2028.     
  2029.     def __init__(self, roots, children, descendp):
  2030.         self.roots = roots[:]
  2031.         self.state = []
  2032.         self.children = children
  2033.         self.descendp = descendp
  2034.  
  2035.     
  2036.     def next(self):
  2037.         if not self.state:
  2038.             if not self.roots:
  2039.                 return None
  2040.             root = self.roots.pop(0)
  2041.             self.state = [
  2042.                 (root, self.children(root))]
  2043.         
  2044.         (node, children) = self.state[-1]
  2045.         if not children:
  2046.             self.state.pop()
  2047.             return self.next()
  2048.         child = children.pop(0)
  2049.         if self.descendp(child):
  2050.             self.state.append((child, self.children(child)))
  2051.         
  2052.         return child
  2053.  
  2054.  
  2055.  
  2056. class ModuleScanner:
  2057.     '''An interruptible scanner that searches module synopses.'''
  2058.     
  2059.     def run(self, callback, key = None, completer = None, onerror = None):
  2060.         if key:
  2061.             key = lower(key)
  2062.         
  2063.         self.quit = False
  2064.         seen = { }
  2065.         for modname in sys.builtin_module_names:
  2066.             if modname != '__main__':
  2067.                 seen[modname] = 1
  2068.                 if key is None:
  2069.                     callback(None, modname, '')
  2070.                 elif not __import__(modname).__doc__:
  2071.                     pass
  2072.                 desc = split('', '\n')[0]
  2073.                 if find(lower(modname + ' - ' + desc), key) >= 0:
  2074.                     callback(None, modname, desc)
  2075.                 
  2076.             find(lower(modname + ' - ' + desc), key) >= 0
  2077.         
  2078.         for importer, modname, ispkg in pkgutil.walk_packages(onerror = onerror):
  2079.             if self.quit:
  2080.                 break
  2081.             
  2082.             if key is None:
  2083.                 callback(None, modname, '')
  2084.                 continue
  2085.             loader = importer.find_module(modname)
  2086.             if hasattr(loader, 'get_source'):
  2087.                 import StringIO
  2088.                 if not source_synopsis(StringIO.StringIO(loader.get_source(modname))):
  2089.                     pass
  2090.                 desc = ''
  2091.                 if hasattr(loader, 'get_filename'):
  2092.                     path = loader.get_filename(modname)
  2093.                 else:
  2094.                     path = None
  2095.             else:
  2096.                 module = loader.load_module(modname)
  2097.                 if not module.__doc__:
  2098.                     pass
  2099.                 desc = ''.splitlines()[0]
  2100.                 path = getattr(module, '__file__', None)
  2101.             if find(lower(modname + ' - ' + desc), key) >= 0:
  2102.                 callback(path, modname, desc)
  2103.                 continue
  2104.         
  2105.         if completer:
  2106.             completer()
  2107.         
  2108.  
  2109.  
  2110.  
  2111. def apropos(key):
  2112.     '''Print all the one-line module summaries that contain a substring.'''
  2113.     
  2114.     def callback(path, modname, desc):
  2115.         if modname[-9:] == '.__init__':
  2116.             modname = modname[:-9] + ' (package)'
  2117.         
  2118.         print modname,
  2119.         if desc:
  2120.             pass
  2121.         print '- ' + desc
  2122.  
  2123.     
  2124.     try:
  2125.         import warnings
  2126.     except ImportError:
  2127.         pass
  2128.  
  2129.     warnings.filterwarnings('ignore')
  2130.     ModuleScanner().run(callback, key)
  2131.  
  2132.  
  2133. def serve(port, callback = None, completer = None):
  2134.     import BaseHTTPServer
  2135.     import mimetools
  2136.     import select
  2137.     
  2138.     class Message(mimetools.Message):
  2139.         
  2140.         def __init__(self, fp, seekable = 1):
  2141.             Message = self.__class__
  2142.             Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)
  2143.             self.encodingheader = self.getheader('content-transfer-encoding')
  2144.             self.typeheader = self.getheader('content-type')
  2145.             self.parsetype()
  2146.             self.parseplist()
  2147.  
  2148.  
  2149.     
  2150.     class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  2151.         
  2152.         def send_document(self, title, contents):
  2153.             
  2154.             try:
  2155.                 self.send_response(200)
  2156.                 self.send_header('Content-Type', 'text/html')
  2157.                 self.end_headers()
  2158.                 self.wfile.write(html.page(title, contents))
  2159.             except IOError:
  2160.                 pass
  2161.  
  2162.  
  2163.         
  2164.         def do_GET(self):
  2165.             path = self.path
  2166.             if path[-5:] == '.html':
  2167.                 path = path[:-5]
  2168.             
  2169.             if path[:1] == '/':
  2170.                 path = path[1:]
  2171.             
  2172.             if path and path != '.':
  2173.                 
  2174.                 try:
  2175.                     obj = locate(path, forceload = 1)
  2176.                 except ErrorDuringImport:
  2177.                     value = None
  2178.                     self.send_document(path, html.escape(str(value)))
  2179.                     return None
  2180.  
  2181.                 if obj:
  2182.                     self.send_document(describe(obj), html.document(obj, path))
  2183.                 else:
  2184.                     self.send_document(path, 'no Python documentation found for %s' % repr(path))
  2185.             else:
  2186.                 heading = html.heading('<big><big><strong>Python: Index of Modules</strong></big></big>', '#ffffff', '#7799ee')
  2187.                 
  2188.                 def bltinlink(name):
  2189.                     return '<a href="%s.html">%s</a>' % (name, name)
  2190.  
  2191.                 names = filter((lambda x: x != '__main__'), sys.builtin_module_names)
  2192.                 contents = html.multicolumn(names, bltinlink)
  2193.                 indices = [
  2194.                     '<p>' + html.bigsection('Built-in Modules', '#ffffff', '#ee77aa', contents)]
  2195.                 seen = { }
  2196.                 for dir in sys.path:
  2197.                     indices.append(html.index(dir, seen))
  2198.                 
  2199.                 contents = heading + join(indices) + '<p align=right>\n<font color="#909090" face="helvetica, arial"><strong>\npydoc</strong> by Ka-Ping Yee <ping@lfw.org></font>'
  2200.                 self.send_document('Index of Modules', contents)
  2201.  
  2202.         
  2203.         def log_message(self, *args):
  2204.             pass
  2205.  
  2206.  
  2207.     
  2208.     class DocServer(BaseHTTPServer.HTTPServer):
  2209.         
  2210.         def __init__(self, port, callback):
  2211.             if not sys.platform == 'mac' or '127.0.0.1':
  2212.                 pass
  2213.             host = 'localhost'
  2214.             self.address = ('', port)
  2215.             self.url = 'http://%s:%d/' % (host, port)
  2216.             self.callback = callback
  2217.             self.base.__init__(self, self.address, self.handler)
  2218.  
  2219.         
  2220.         def serve_until_quit(self):
  2221.             import select
  2222.             self.quit = False
  2223.             while not self.quit:
  2224.                 (rd, wr, ex) = select.select([
  2225.                     self.socket.fileno()], [], [], 1)
  2226.                 if rd:
  2227.                     self.handle_request()
  2228.                     continue
  2229.  
  2230.         
  2231.         def server_activate(self):
  2232.             self.base.server_activate(self)
  2233.             if self.callback:
  2234.                 self.callback(self)
  2235.             
  2236.  
  2237.  
  2238.     DocServer.base = BaseHTTPServer.HTTPServer
  2239.     DocServer.handler = DocHandler
  2240.     DocHandler.MessageClass = Message
  2241.     
  2242.     try:
  2243.         DocServer(port, callback).serve_until_quit()
  2244.     except (KeyboardInterrupt, select.error):
  2245.         pass
  2246.     finally:
  2247.         if completer:
  2248.             completer()
  2249.         
  2250.  
  2251.  
  2252.  
  2253. def gui():
  2254.     '''Graphical interface (starts web server and pops up a control window).'''
  2255.     
  2256.     class GUI:
  2257.         
  2258.         def __init__(self, window, port = 7464):
  2259.             self.window = window
  2260.             self.server = None
  2261.             self.scanner = None
  2262.             import Tkinter
  2263.             self.server_frm = Tkinter.Frame(window)
  2264.             self.title_lbl = Tkinter.Label(self.server_frm, text = 'Starting server...\n ')
  2265.             self.open_btn = Tkinter.Button(self.server_frm, text = 'open browser', command = self.open, state = 'disabled')
  2266.             self.quit_btn = Tkinter.Button(self.server_frm, text = 'quit serving', command = self.quit, state = 'disabled')
  2267.             self.search_frm = Tkinter.Frame(window)
  2268.             self.search_lbl = Tkinter.Label(self.search_frm, text = 'Search for')
  2269.             self.search_ent = Tkinter.Entry(self.search_frm)
  2270.             self.search_ent.bind('<Return>', self.search)
  2271.             self.stop_btn = Tkinter.Button(self.search_frm, text = 'stop', pady = 0, command = self.stop, state = 'disabled')
  2272.             if sys.platform == 'win32':
  2273.                 self.stop_btn.pack(side = 'right')
  2274.             
  2275.             self.window.title('pydoc')
  2276.             self.window.protocol('WM_DELETE_WINDOW', self.quit)
  2277.             self.title_lbl.pack(side = 'top', fill = 'x')
  2278.             self.open_btn.pack(side = 'left', fill = 'x', expand = 1)
  2279.             self.quit_btn.pack(side = 'right', fill = 'x', expand = 1)
  2280.             self.server_frm.pack(side = 'top', fill = 'x')
  2281.             self.search_lbl.pack(side = 'left')
  2282.             self.search_ent.pack(side = 'right', fill = 'x', expand = 1)
  2283.             self.search_frm.pack(side = 'top', fill = 'x')
  2284.             self.search_ent.focus_set()
  2285.             if not sys.platform == 'win32' or 8:
  2286.                 pass
  2287.             font = ('helvetica', 10)
  2288.             self.result_lst = Tkinter.Listbox(window, font = font, height = 6)
  2289.             self.result_lst.bind('<Button-1>', self.select)
  2290.             self.result_lst.bind('<Double-Button-1>', self.goto)
  2291.             self.result_scr = Tkinter.Scrollbar(window, orient = 'vertical', command = self.result_lst.yview)
  2292.             self.result_lst.config(yscrollcommand = self.result_scr.set)
  2293.             self.result_frm = Tkinter.Frame(window)
  2294.             self.goto_btn = Tkinter.Button(self.result_frm, text = 'go to selected', command = self.goto)
  2295.             self.hide_btn = Tkinter.Button(self.result_frm, text = 'hide results', command = self.hide)
  2296.             self.goto_btn.pack(side = 'left', fill = 'x', expand = 1)
  2297.             self.hide_btn.pack(side = 'right', fill = 'x', expand = 1)
  2298.             self.window.update()
  2299.             self.minwidth = self.window.winfo_width()
  2300.             self.minheight = self.window.winfo_height()
  2301.             self.bigminheight = self.server_frm.winfo_reqheight() + self.search_frm.winfo_reqheight() + self.result_lst.winfo_reqheight() + self.result_frm.winfo_reqheight()
  2302.             self.bigwidth = self.minwidth
  2303.             self.bigheight = self.bigminheight
  2304.             self.expanded = 0
  2305.             self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
  2306.             self.window.wm_minsize(self.minwidth, self.minheight)
  2307.             self.window.tk.willdispatch()
  2308.             import threading
  2309.             threading.Thread(target = serve, args = (port, self.ready, self.quit)).start()
  2310.  
  2311.         
  2312.         def ready(self, server):
  2313.             self.server = server
  2314.             self.title_lbl.config(text = 'Python documentation server at\n' + server.url)
  2315.             self.open_btn.config(state = 'normal')
  2316.             self.quit_btn.config(state = 'normal')
  2317.  
  2318.         
  2319.         def open(self, event = None, url = None):
  2320.             if not url:
  2321.                 pass
  2322.             url = self.server.url
  2323.             
  2324.             try:
  2325.                 import webbrowser
  2326.                 webbrowser.open(url)
  2327.             except ImportError:
  2328.                 if sys.platform == 'win32':
  2329.                     os.system('start "%s"' % url)
  2330.                 elif sys.platform == 'mac':
  2331.                     
  2332.                     try:
  2333.                         import ic
  2334.                     except ImportError:
  2335.                         pass
  2336.  
  2337.                     ic.launchurl(url)
  2338.                 else:
  2339.                     rc = os.system('netscape -remote "openURL(%s)" &' % url)
  2340.                     if rc:
  2341.                         os.system('netscape "%s" &' % url)
  2342.                     
  2343.             except:
  2344.                 sys.platform == 'win32'
  2345.  
  2346.  
  2347.         
  2348.         def quit(self, event = None):
  2349.             if self.server:
  2350.                 self.server.quit = 1
  2351.             
  2352.             self.window.quit()
  2353.  
  2354.         
  2355.         def search(self, event = None):
  2356.             key = self.search_ent.get()
  2357.             self.stop_btn.pack(side = 'right')
  2358.             self.stop_btn.config(state = 'normal')
  2359.             self.search_lbl.config(text = 'Searching for "%s"...' % key)
  2360.             self.search_ent.forget()
  2361.             self.search_lbl.pack(side = 'left')
  2362.             self.result_lst.delete(0, 'end')
  2363.             self.goto_btn.config(state = 'disabled')
  2364.             self.expand()
  2365.             import threading
  2366.             if self.scanner:
  2367.                 self.scanner.quit = 1
  2368.             
  2369.             self.scanner = ModuleScanner()
  2370.             threading.Thread(target = self.scanner.run, args = (self.update, key, self.done)).start()
  2371.  
  2372.         
  2373.         def update(self, path, modname, desc):
  2374.             if modname[-9:] == '.__init__':
  2375.                 modname = modname[:-9] + ' (package)'
  2376.             
  2377.             if not desc:
  2378.                 pass
  2379.             self.result_lst.insert('end', modname + ' - ' + '(no description)')
  2380.  
  2381.         
  2382.         def stop(self, event = None):
  2383.             if self.scanner:
  2384.                 self.scanner.quit = 1
  2385.                 self.scanner = None
  2386.             
  2387.  
  2388.         
  2389.         def done(self):
  2390.             self.scanner = None
  2391.             self.search_lbl.config(text = 'Search for')
  2392.             self.search_lbl.pack(side = 'left')
  2393.             self.search_ent.pack(side = 'right', fill = 'x', expand = 1)
  2394.             if sys.platform != 'win32':
  2395.                 self.stop_btn.forget()
  2396.             
  2397.             self.stop_btn.config(state = 'disabled')
  2398.  
  2399.         
  2400.         def select(self, event = None):
  2401.             self.goto_btn.config(state = 'normal')
  2402.  
  2403.         
  2404.         def goto(self, event = None):
  2405.             selection = self.result_lst.curselection()
  2406.             if selection:
  2407.                 modname = split(self.result_lst.get(selection[0]))[0]
  2408.                 self.open(url = self.server.url + modname + '.html')
  2409.             
  2410.  
  2411.         
  2412.         def collapse(self):
  2413.             if not self.expanded:
  2414.                 return None
  2415.             self.result_frm.forget()
  2416.             self.result_scr.forget()
  2417.             self.result_lst.forget()
  2418.             self.bigwidth = self.window.winfo_width()
  2419.             self.bigheight = self.window.winfo_height()
  2420.             self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
  2421.             self.window.wm_minsize(self.minwidth, self.minheight)
  2422.             self.expanded = 0
  2423.  
  2424.         
  2425.         def expand(self):
  2426.             if self.expanded:
  2427.                 return None
  2428.             self.result_frm.pack(side = 'bottom', fill = 'x')
  2429.             self.result_scr.pack(side = 'right', fill = 'y')
  2430.             self.result_lst.pack(side = 'top', fill = 'both', expand = 1)
  2431.             self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))
  2432.             self.window.wm_minsize(self.minwidth, self.bigminheight)
  2433.             self.expanded = 1
  2434.  
  2435.         
  2436.         def hide(self, event = None):
  2437.             self.stop()
  2438.             self.collapse()
  2439.  
  2440.  
  2441.     import Tkinter
  2442.     
  2443.     try:
  2444.         root = Tkinter.Tk()
  2445.         
  2446.         try:
  2447.             gui = GUI(root)
  2448.             root.mainloop()
  2449.         finally:
  2450.             root.destroy()
  2451.  
  2452.     except KeyboardInterrupt:
  2453.         pass
  2454.  
  2455.  
  2456.  
  2457. def ispath(x):
  2458.     if isinstance(x, str):
  2459.         pass
  2460.     return find(x, os.sep) >= 0
  2461.  
  2462.  
  2463. def cli():
  2464.     '''Command-line interface (looks at sys.argv to decide what to do).'''
  2465.     import getopt
  2466.     
  2467.     class BadUsage:
  2468.         pass
  2469.  
  2470.     scriptdir = os.path.dirname(sys.argv[0])
  2471.     if scriptdir in sys.path:
  2472.         sys.path.remove(scriptdir)
  2473.     
  2474.     sys.path.insert(0, '.')
  2475.     
  2476.     try:
  2477.         (opts, args) = getopt.getopt(sys.argv[1:], 'gk:p:w')
  2478.         writing = 0
  2479.         for opt, val in opts:
  2480.             if opt == '-g':
  2481.                 gui()
  2482.                 return None
  2483.             if opt == '-k':
  2484.                 apropos(val)
  2485.                 return None
  2486.             if opt == '-p':
  2487.                 
  2488.                 try:
  2489.                     port = int(val)
  2490.                 except ValueError:
  2491.                     opt == '-k'
  2492.                     opt == '-k'
  2493.                     opt == '-g'
  2494.                     raise BadUsage
  2495.                 except:
  2496.                     opt == '-k'
  2497.  
  2498.                 
  2499.                 def ready(server):
  2500.                     print 'pydoc server ready at %s' % server.url
  2501.  
  2502.                 
  2503.                 def stopped():
  2504.                     print 'pydoc server stopped'
  2505.  
  2506.                 serve(port, ready, stopped)
  2507.                 return None
  2508.             if opt == '-w':
  2509.                 writing = 1
  2510.                 continue
  2511.             opt == '-p'
  2512.         
  2513.         if not args:
  2514.             raise BadUsage
  2515.         args
  2516.         for arg in args:
  2517.             if ispath(arg) and not os.path.exists(arg):
  2518.                 print 'file %r does not exist' % arg
  2519.                 break
  2520.             
  2521.             
  2522.             try:
  2523.                 if ispath(arg) and os.path.isfile(arg):
  2524.                     arg = importfile(arg)
  2525.                 
  2526.                 if writing:
  2527.                     if ispath(arg) and os.path.isdir(arg):
  2528.                         writedocs(arg)
  2529.                     else:
  2530.                         writedoc(arg)
  2531.                 else:
  2532.                     help.help(arg)
  2533.             continue
  2534.             except ErrorDuringImport:
  2535.                 value = None
  2536.                 print value
  2537.                 continue
  2538.             
  2539.  
  2540.     except (getopt.error, BadUsage):
  2541.         cmd = os.path.basename(sys.argv[0])
  2542.         print "pydoc - the Python documentation tool\n\n%s <name> ...\n    Show text documentation on something.  <name> may be the name of a\n    Python keyword, topic, function, module, or package, or a dotted\n    reference to a class or function within a module or module in a\n    package.  If <name> contains a '%s', it is used as the path to a\n    Python source file to document. If name is 'keywords', 'topics',\n    or 'modules', a listing of these things is displayed.\n\n%s -k <keyword>\n    Search for a keyword in the synopsis lines of all available modules.\n\n%s -p <port>\n    Start an HTTP server on the given port on the local machine.\n\n%s -g\n    Pop up a graphical interface for finding and serving documentation.\n\n%s -w <name> ...\n    Write out the HTML documentation for a module to a file in the current\n    directory.  If <name> contains a '%s', it is treated as a filename; if\n    it names a directory, documentation is written for all the contents.\n" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
  2543.  
  2544.  
  2545. if __name__ == '__main__':
  2546.     cli()
  2547.  
  2548.